<script setup>
  import { ref, reactive } from 'vue'
  import { login } from '@/apis/user'
  import { useUserStore } from '@/stores/user'
  import { toast } from '@/utils/utils.js'
  import { onLoad } from '@dcloudio/uni-app'

  let query = {}
  onLoad((_query) => {
    query = _query
    console.log(query)
  })

  // 表单元素的 ref 属性
  const accountForm = ref()

  // 表单数据
  const formData = ref({
    account: 'xbsj001',
    password: '123456',
  })

  // 定义表单数据验证规则
  const accountRules = ref({
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
      ],
    },
  })

  // 监听表单的提交
  async function onFormSubmit() {
    try {
      // 验证通过
      await accountForm.value.validate()
      // 表单的数据
      const { code, data } = await login(formData.value)
      // 检测接口是否调用成功
      if (code !== 200) return uni.utils.toast('登录失败，请重试！')
      // 持久化存储用户登录状态
      // const { setToken } = useUserStore()
      const { setToken } = useUserStore()
      // userStore.token = data
      setToken(data)
      toast('登录成功', 'success')
      // uni[query.returnType]({ url: query.returnURL })
      if (query.returnURL) {
        if (query.returnType === 'switchTab') {
          console.log('有回跳地址，且可以走switchTab跳转')
          uni.switchTab({
            url: query.returnURL,
          })
        } else if (query.returnType === 'redirectTo') {
          console.log('有回跳地址，走redirectTo跳转')
          uni.redirectTo({
            url: query.returnURL,
          })
        }
      } else {
        console.log('默认跳转主页')
        uni.switchTab({
          url: '/pages/my/index',
        })
      }
    } catch (err) {
      // 验证失败
      console.log(err)
      console.log('报错了')
    }
  }
</script>

<template>
  <uni-forms class="login-form" ref="accountForm" :rules="accountRules" :model="formData">
    <uni-forms-item name="account">
      <input
        type="text"
        v-model="formData.account"
        placeholder="请输入账号"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        v-model="formData.password"
        type="text"
        placeholder="请输入密码"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button @click="onFormSubmit" class="submit-button">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
